package com.easylinkin.linkappapi.facerecognition.config;

import com.aliyun.oss.OSSClient;
import com.easylinkin.linkappapi.facerecognition.service.oss.ObjectStorageInternalService;
import com.easylinkin.linkappapi.facerecognition.service.oss.ObjectStorageOutsideService;
import com.easylinkin.linkappapi.facerecognition.service.oss.impl.AliObjectStorageInternalService;
import com.easylinkin.linkappapi.facerecognition.service.oss.impl.AliObjectStorageService;
import com.easylinkin.linkappapi.facerecognition.service.oss.impl.MinIoObjectStorageInternalService;
import com.easylinkin.linkappapi.facerecognition.service.oss.impl.MinIoObjectStorageService;
import io.minio.MinioClient;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OssClientConfig {

    @Value("${oss.type}")
    private String ossType;

    @Value("${oss.bucket}")
    private String bucket;

    @Value("${oss.dir}")
    private String dir;

    @Value("${oss.accessKeyId}")
    private String accessKeyId;

    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${oss.endPoint}")
    private String endPoint;

    @Value("${oss.readHost}")
    private String aliReadHost;

    public MinioClient minioClient() {
        try {
            return new MinioClient(endPoint, accessKeyId, accessKeySecret);
        } catch (InvalidEndpointException | InvalidPortException e) {
            e.printStackTrace();
        }

        return null;
    }

    public OSSClient aliOssClient() {
        return new OSSClient(aliReadHost, accessKeyId, accessKeySecret);
    }

    public OSSClient aliOssInternalClient() {
        return new OSSClient(endPoint, accessKeyId, accessKeySecret);
    }

    @Bean
    public ObjectStorageOutsideService oss() {
        if ("minio".equalsIgnoreCase(ossType)) {
            return new MinIoObjectStorageService(minioClient());
        } else {
            return new AliObjectStorageService(aliOssClient());
        }
    }

    @Bean
    public ObjectStorageInternalService ossInternal() {
        if ("minio".equalsIgnoreCase(ossType)) {
            return new MinIoObjectStorageInternalService(minioClient());
        } else {
            return new AliObjectStorageInternalService(aliOssInternalClient());
        }
    }

    public String getBucket() {
        return bucket;
    }

    public String getDir() {
        return dir;
    }
}
